﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 玩家剑武器的碰撞体，负责造成伤害。
/// </summary>
public class SwordCollider : MonoBehaviour
{
    /// the collision mask that will get hit
    public LayerMask CollisionMask;
    /// 碰撞到的时候的粒子特效
    public GameObject HitEffect;
    /// 这个碰撞体的持有者
    public GameObject Owner;

    [SerializeField]
    private DamageInfo AtkDamage;
    [SerializeField]
    private DamageInfo DefaultDamage = new DamageInfo(0);

    public void SetDamage(DamageInfo info)
    {
        AtkDamage = info;
    }

    public void Reset()
    {
        AtkDamage = DefaultDamage;
    }

    private void OnTriggerEnter2D(Collider2D collider)
    {
        //  layer不对的话 返回
        if (CollisionMask.Contains(collider.gameObject) == false)
        {
            return;
        }

        Debug.Log("  进入jiance ");


        // 如果是持有者的话  返回
        if (collider.gameObject == Owner)
        {
            return;
        }

        ICanTakeDamage takeDamage = collider.gameObject.GetComponent<ICanTakeDamage>();
        if (takeDamage != null)
        {
            //  获取到正确的对象组件，造成伤害
            OnCollideTakeDamage(collider, takeDamage);
            return;
        }
        //  撞到的是 其他
        OnCollideOther(collider);

    }


    void OnCollideTakeDamage(Collider2D collider, ICanTakeDamage takeDamage)
    {
        if (null != HitEffect)
            Instantiate(HitEffect, collider.transform.position, collider.transform.rotation);

        takeDamage.TakeDamage(AtkDamage, gameObject);

        Debug.LogFormat(collider, "对 {0} 造成了 {1} 伤害", collider.gameObject.name, AtkDamage.damage);

        DisableMeleeWeapon();
    }

    void OnCollideOther(Collider2D collider)
    {
        DisableMeleeWeapon();
    }

    void DisableMeleeWeapon()
    {
        // if you have longer lasting melee animations, you might want to disable the weapon's collider after it hits something, until the end of the animation.
    }
}
